package com.gls.service.zuul.provider;

import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lizhiyong
 */
@Component
@Primary
public class DocumentationProvider implements SwaggerResourcesProvider {

    private final static String ROUTE_ID_PREFIX = "service";
    private final RouteLocator routeLocator;

    public DocumentationProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        //在这里遍历的时候，可以排除掉敏感微服务的路由
        routes.forEach(route -> {
            String name = route.getId();
            if (!name.startsWith(ROUTE_ID_PREFIX)) {
                return;
            }
            String location = route.getFullPath().replace("**", "v2/api-docs");
            String version = "2.0";
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(name);
            swaggerResource.setLocation(location);
            swaggerResource.setSwaggerVersion(version);
            resources.add(swaggerResource);
        });

        return resources;
    }

}
